package org.fei.demo.basic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class RabbitProducer {

    private static final String EXCHANGE_NAME = "e.MQ.BASIC.TEST";
    private static final String ROUTING_KEY = "r.MQ.BASIC.TEST";
    private static final String QUEUE_NAME = "q.MQ.BASIC.TEST";
    private static final String IP_ADDRESS = "192.168.1.11";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root123";
    private static final String VHOST = "/";
    private static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(USERNAME);
        factory.setPassword(PASSWORD);
        factory.setVirtualHost(VHOST);
        factory.setHost(IP_ADDRESS);
        factory.setPort(PORT);

        //创建连接
        Connection connection= factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();
        //创建一个 type="direct"、持久化的、非自动删除的交换器
        channel.exchangeDeclare(EXCHANGE_NAME,"direct",true,false,null);
        //创建一个持久化、非排他的、非自动删除的队列
        channel.queueDeclare(QUEUE_NAME,true,false,false, null);
        //将交换器与队列通过路由键绑定
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,ROUTING_KEY);

        //发送消息
        String message = "Hello, RabbitMQ!";
        channel.basicPublish(
                EXCHANGE_NAME,
                ROUTING_KEY,
                MessageProperties.PERSISTENT_TEXT_PLAIN,
                message.getBytes(StandardCharsets.UTF_8));

        //关闭资源
        channel.close();
        connection.close();
    }
}
